<?php
/**
 * A generic parent class for File and Folder
 * @author Erko Risthein <erko@risthein.ee>
 * @copyright Copyright (C) 2009 Erko Risthein
 * @link http://erko.risthein.ee/decode/
 * @license http://www.gnu.org/licenses/ GNU General Public License
 * @package decode_explorer
 */
class Filesystem {
	protected $url;
	protected $name;
	protected $date;
	
	/**
	 * @param string $path to the object
	 */
	function __construct($path) {
		$this->url = Helper::format_url($path);
		$this->name = $this->parse_name($path);
		$this->date = $this->get_filemtime($path);
		//data formatting
		$this->date = date('Y-m-d', $this->date);
	}
	
	/**
	 * Parses the file name from the path and makes sure its encoded in UTF-8
	 * @param string $path to the file
	 * @return string parsed name
	 */
	private function parse_name($path) {
		$filename = $this->get_basename($path);
		return $this->is_utf8($filename) ? $filename : utf8_encode($filename);
	}
	
	/**
	 * Gets the basename from the path
	 * @param string $path to the file
	 * @return string basename
	 */
	private function get_basename($path) {
		return mb_substr($path, mb_strrpos($path, '/') + 1);
	}
	
	/**
	 * Checks if the given string is encoded in UTF-8 
	 * @param string $str given string
	 * @return boolean
	 */
	private function is_utf8($str) {
		return preg_match('/^.{1}/us', $str);
	}
	
	/**
	 * Gets file modification time
	 * @param string $path to the file
	 * @return string file modification time
	 */
	private function get_filemtime($path) {
		$filemtime = @filemtime($path);
		if ($filemtime == false && function_exists('exec') && strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { //for files over 2GB
			$filemtime = exec('stat -c %Y ' . escapeshellarg($path));
		}
		return $filemtime;
	}	
	
	/**
	 * @return string object url
	 */
	public final function get_url() {
		return $this->url;
	}
	
	/**
	 * @return string object name
	 */
	public function get_name() {
		return $this->name;
	}
	
	/**
	 * @return string formatted last-modified date
	 */
	public final function get_date() {
		return $this->date;
	}
	
	/**
	 * Formats the filesize from bytes to a more readable form
	 * @param int $filesize in bytes
	 * @return string formatted file size
	 */
	public static final function format_filesize(&$filesize) {
		$filesize /= 1024; //Bytes to kiloBytes
		$suffixes = array('kB', 'MB', 'GB', 'TB');
		for ($i = 0; ($i < 4 && ($filesize / 1024) >= 1); $i++) { //4 = suffixes count
			$filesize /= 1024;
		}
		$precision = ($i == 0) ? 0 : 1; //round kiloBytes differently
		$filesize = round($filesize, $precision) . ' ' . $suffixes[$i];
	}
}
?>